﻿using System;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
using Newtonsoft.Json;
using RuneLog.GrandExchange.GraphView;

namespace RuneLog.GrandExchange
{
    public partial class LookupForm : Form
    {
        /// <summary>
        /// The base URL for an item on the grand exchange
        /// </summary>
        private const string baseUrl = "http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=";

        /// <summary>
        /// The file that contains the list of items names and IDs
        /// </summary>
        private const string dataFile = "resources\\ItemList.sqlite";
        /// <summary>
        /// Looks up IDs and Names of items.
        /// </summary>
        private ItemIdProvider provider = new ItemIdProvider(dataFile);

        /// <summary>
        /// Constructs a new a new Form that can be used to lookup information on the Grand Exchange
        /// </summary>
        public LookupForm()
        {
            InitializeComponent();
            var bitmap = new Bitmap("resources\\largepile.png");
            this.Icon = Icon.FromHandle(bitmap.GetHicon());
        }

        /// <summary>
        /// Called when the Search button is pressed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchButton_Click(object sender, EventArgs e)
        {
            LoadList();
        }

        /// <summary>
        /// Called when the user hits enter when the Focus is on this object.
        /// <remarks>This method is the equivalent of the search button</remarks>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)Keys.Enter)
            {
                return;
            }
            e.Handled = true;
            LoadList();
        }

        /// <summary>
        /// Loads the items from a list depending on what is entered in the search box.
        /// </summary>
        private void LoadList()
        {
            resultListBox.Items.Clear();
            string[] list = provider.GetItems(searchTextBox.Text).ToArray();
            foreach (string item in list)
            {
                resultListBox.Items.Add(item.Replace("#$", "'"));
            }
        }

        /// <summary>
        /// Called when the user selects an item from the list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resultListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadItem(resultListBox.GetItemText(resultListBox.SelectedItem));
        }    
    
        /// <summary>
        /// Starts the load sequence of an item
        /// </summary>
        /// <param name="name">The Full name of the item</param>
        private void LoadItem(string name)
        {
            int itemID = provider.GetId(name);
            var client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DataLoaded);
            client.DownloadStringAsync(new Uri(baseUrl + itemID.ToString()));
        }

        /// <summary>
        /// Called when loading of the item is fininshed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataLoaded(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null) return;
            Item item = JsonConvert.DeserializeObject<RootObject>(e.Result).Item;
            LoadDetails(item);
        }

        /// <summary>
        /// Loads an Item into the userinterface
        /// </summary>
        /// <param name="item">The item that we should load</param>
        private void LoadDetails(Item item)
        {
            if (itemImage.WaitOnLoad) itemImage.CancelAsync();
            itemImage.Image = null;
            itemImage.LoadAsync(item.Icon.Replace("sprite", "big"));

            label180DayChange.Text = "180 Day Change: " + item.Day180.Change;
            label30DayChange.Text = "30 Day Change: " + item.Day30.Change;
            label90DayChange.Text = "90 Day Change: " + item.Day90.Change;
            labelChangeToday.Text = "Today's Change: " + item.Today.Price;
            labelCurrentPrice.Text = "Current Price: " + item.Current.Price;
            labelDesc.Text = item.Description;
            labelItemName.Text = item.Name;
        }

        private void graphBtn_Click(object sender, EventArgs e)
        {
            new GraphViewer(new GraphData(provider.GetId(labelItemName.Text)), itemImage.Image, labelItemName.Text).Show();
        }
    }
}
